// 获取学员列表数据，并渲染
function renderStudent() {
  let list = document.querySelector('.list')
  axios({
    url: 'http://ajax-api.itheima.net/students',
    headers: {
      Authorization: localStorage.getItem('token')
    },
  }).then(result => {
    // console.log(result);
    let str = result.data.data.map(function (item, index) {
      return `
                    <tr>
                      <td>${item.name}</td>
                      <td>${item.age}</td>
                      <td>${item.gender ? '女' : '男'}</td>
                      <td>第${item.group}组</td>
                      <td>${item.hope_salary}</td>
                      <td>${item.salary}</td>
                      <td>${item.province}${item.city}${item.area}</td>
                      <td>
                        <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen" data-id="${item.id}"></i></a>
                        <a href="javascript:;" class="text-danger"><i class="bi bi-trash" data-id="${item.id}"></i></a>
                      </td>
                    </tr>
      `
    })
    list.innerHTML = str.join('')
  })

}
renderStudent()
// ==============================省市县联动================================
let sheng = '<option value="">--省份--</option>'
let shi = '<option value="">--城市--</option>'
let xian = '<option value="">--地区--</option>'
let province = document.querySelector('[name=province]')
let city = document.querySelector('[name=city]')
let area = document.querySelector('[name=area]')
// 获取省，并渲染
axios({
  url: '/api/province',
}).then(result => {
  let newArr = result.data.data.map(item => `<option value="${item}">${item}</option>`)
  province.innerHTML = sheng + newArr.join('')
})
// 切换省的时候，获取市，并渲染
province.addEventListener('change', function () {
  // 切换省的时候重置区县
  area.innerHTML = xian
  axios({
    url: '/api/city',
    params: {
      pname: province.value
    }
  }).then(result => {
    let newArr = result.data.data.map(item => `<option value="${item}">${item}</option>`)
    city.innerHTML = shi + newArr.join('')
  })
})
// 市切换的时候获取区县并渲染
city.addEventListener('change', function () {
  axios({
    url: '/api/area',
    params: {
      pname: province.value,
      cname: city.value
    }
  }).then(result => {
    let newArr = result.data.data.map(item => `<option value="${item}">${item}</option>`)
    area.innerHTML = xian + newArr.join('')
  })
})
// ==============================添加学员================================
// 模态框的使用
let addModal = new bootstrap.Modal(document.querySelector('#modal'))
// 点击+显示
document.querySelector('#openModal').addEventListener('click', function () {
  addModal.show()
})
// 点击确认隐藏
document.querySelector('#submit').addEventListener('click', function () {
  // 获取表单各项的值
  // 检查是否是接口需要数据
  let data = val(document.querySelector('#form'))
  // 检查数据
  // console.log(data);
  data.age = +data.age
  data.gender = +data.gender
  data.group = +data.group
  data.hope_salary = +data.hope_salary
  data.salary = +data.salary
  let id=document.querySelector('.modal-title').dataset.id
  if(document.querySelector('.modal-title').innerHTML==='添加成员'){
    // Ajax提交
    axios({
      url: '/students',
      data,
      method: 'post'
    }).then(res => {
      message.success(res.data.message)//提示
      document.querySelector('#form').reset()//重置表单
      renderStudent()//重新渲染
      addModal.hide()
    })

  }else{
    axios({
      url:`/students/${id}`,
      method:'put',
      data
    }).then(res=>{
      message.success('修改成功')
      renderStudent()
      addModal.hide()
    })
  }
})


// ==============================删除学员================================
document.querySelector('tbody').addEventListener('click', async function (e) {
  if (e.target.classList.contains('bi-trash')) {
    let id = e.target.dataset.id
    axios({
      url: `/students/${id}`,
      method: 'delete'
    }).then(res => {
      message.success('删除成功')//提示
      renderStudent()
    })
  }

  //============================编辑功能================
  if (e.target.classList.contains('bi-pen')) {
    let id = e.target.dataset.id
    document.querySelector('.modal-title').innerHTML = '修改数据'
    document.querySelector('.modal-title').setAttribute('data-id', id)
    addModal.show()
    // 发送请求，获取当前修改的学员详细信息
    let result = await axios({
      url: `/students/${id}`
    })
    // console.log(result.data.data);
    // 获取城市和区域，渲染到第二个第三个下拉框
    let res1 = await axios({
      url: '/api/city',
      params: {
        pname: result.data.data.province
      }
    })
    let res2 = await axios({
      url: '/api/area',
      params: {
        pname: result.data.data.province,
        cname: result.data.data.city,
      }
    })
    // console.log(res1);
    let newArr1 = res1.data.data.map(item => `<option value="${item}">${item}</option>`)
    city.innerHTML = shi + newArr1.join('')
    let newArr2 = res2.data.data.map(item => `<option value="${item}">${item}</option>`)
    area.innerHTML = xian + newArr2.join('')
    // 数据回填
    val(document.querySelector('#form'), result.data.data)
  }
})


// 退出按钮
document.querySelector('#logout').addEventListener('click',function(){
  localStorage.removeItem('token')
  location.href='login.html'
})

